package com.wsb.wetchat.service.impl;

import com.wsb.wetchat.common.CommonResult;
import com.wsb.wetchat.dao.Product;
import com.wsb.wetchat.exption.BussinesExpetion;
import com.wsb.wetchat.exption.ExpectionEnum;
import com.wsb.wetchat.mapper.ProductMapper;
import com.wsb.wetchat.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wang shaobo
 * @date 2022/6/30  15:57
 */
@Service
@Slf4j
public class ProductServiceImpl implements ProductService {

    @Autowired
    ProductMapper productMapper;


    Lock lock = new ReentrantLock();

    @Override
    public int queryProStock(int id) {

        //
        return productMapper.getProductStock(id);


    }

    @Override

    public CommonResult decreaseStock(int id, int stock) {

        lock.lock();
        try {
            Product product = productMapper.queryInfo(id);
            String name = Thread.currentThread().getName();
            log.info(name + "查询剩余数量:" + product.getStock() + ",购买数量:" + stock);
            if (product == null || product.getStock() < 0 || product.getStock() < stock) {
                return new CommonResult(500, "剩余数量:" + product.getStock() + ",新购:" + stock + ",余额不足", null);
            }


            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (Exception e) {

            }

            int i = productMapper.decreaseProductStock(id, stock, product.getVersion());
            if (i < 1) {
                return new CommonResult(500, "成功购买:" + stock, "购买失败");
            }

            return new CommonResult(200, "成功购买:" + stock, null);
        } catch (Exception e) {
            return new CommonResult(500, "异常", e.getMessage());
        } finally {
            lock.unlock();
        }


    }
}
